    import Login from './pages/Login.vue'
    import NavPage from './pages/NavPage.vue'
    import {createRouter,createWebHashHistory,} from 'vue-router'
    import type { RouteRecordRaw } from 'vue-router';
    import { getUserInfoApi } from './apis/user'
import { filterData } from './util/global';
// 路由权限
const dynamicRoutes=[
    {path:'home',name:"home", component:()=>import("./pages/Home.vue"),roles:["超级管理员"],meta:{roles:["超级管理员"]}},
        {path:'shopList',name:"shopList",component:()=>import("./pages/shop/ShopList.vue"),},
        {path:'addShop', name:"addShop",component:()=>import("./pages/shop/AddShop.vue"),roles:["超级管理员"],meta:{roles:["超级管理员"]}},
        {path:'accountList',name:"accountList",component:()=>import("./pages/account/AccountList.vue")},
        {path:'addAccount',name:"addAccount",component:()=>import("./pages/account/AddAcount.vue"),roles:["超级管理员"],meta:{roles:["超级管理员"]}},
        {path:'profile',name:"profile",component:()=>import("./pages/Profile.vue")},
        {path:"auth",name:"auth",component:()=>import('./pages/auth.vue')},
        {path:"/:pathMatch(.*)*",name:"notFound",component:()=>import("./pages/NotFound.vue")},
]
const routes:RouteRecordRaw[]=[
    {path:"/",redirect:"/login"},
    {path:"/login",component:Login},
    {path:"/nav",name:"nav", component:NavPage,
    
    children:dynamicRoutes},
]
export const router=createRouter({
    history:createWebHashHistory(),
    routes
})

    // initialRoutes()
    export function initialRoutes(){
        const userInfo=localStorage.userInfo;
        let routes=dynamicRoutes;
        // const role = JSON.parse(localStorage.userInfo).role;
       
        if(userInfo){
             routes=filterData(dynamicRoutes,userInfo.role);
        }
        dynamicRoutes.forEach(item=>{
            if(router.hasRoute(item.name)){
                router.removeRoute(item.name)
            }
           
        })
        routes.forEach(item=>{
            router.addRoute("nav",item)
        })
    }


//路由守卫，登录权限/路由权限
    const writeList=['/login','/']

    router.beforeEach((to,from,next)=>{
        if(writeList.includes(from.path)&&!writeList.includes(to.path)){
            const token=localStorage.token
            if(!token){
                next('/login')
            }else{
                getUserInfoApi()
                .then(()=>{
                    next()
                })
    
            }
            
        }
        else if(!writeList.includes(from.path) && !writeList.includes(to.path)){
            const curRole = JSON.parse(localStorage.userInfo).role;
            if(!to.meta.roles || (to.meta.roles as any).includes(curRole)){
                //如果meta中没有roles字段或者有roles，且roles包含了当前登录人的角色
                next();
            }else{
                next(from.path);
            }
        }
        else{
            next()
        }  
    })

